package com.euond.permission.service.impl;

import com.euond.common.core.service.RedisService;
import com.euond.common.core.service.impl.BaseServiceImpl;
import com.euond.common.utils.SqlUtils;
import com.euond.common.utils.ThreadLocals;
import com.euond.permission.dto.DataPrivilegeDtlDto;
import com.euond.permission.dto.DataPrivilegeDto;
import com.euond.permission.entities.DataPrivilege;
import com.euond.permission.mapper.DataPrivilegeMapper;
import com.euond.permission.service.DataPrivilegeDtlService;
import com.euond.permission.service.DataPrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Created by user on 2018/1/6.
 */
@Service
public class DataPrivilegeServiceImpl extends BaseServiceImpl<DataPrivilegeMapper,DataPrivilege> implements DataPrivilegeService {

    @Autowired
    private DataPrivilegeDtlService dataPrivilegeDtlService;
    @Autowired
    private RedisService redisService;
    private static Long redis_key_exp = Long.valueOf(7200L);

    /*
    * 重写基类deleteBatchIds方法
    */
    @Override
    @Transactional
    public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
        //先删明细，后删主表
        for(int i=0;i<idList.toArray().length;i++){
            dataPrivilegeDtlService.deleteDataPrivilegeDtlByPrivilegeId(Long.valueOf(idList.toArray()[i].toString()));
        }
        return super.deleteBatchIds(idList);
    }

    /*
    * 重写基类deleteById方法
    */
    @Override
    @Transactional
    public boolean deleteById(Serializable id){
        dataPrivilegeDtlService.deleteDataPrivilegeDtlByPrivilegeId(Long.valueOf(id.toString()));
        return super.deleteById(id);
    }

    /*
    * 获取所有数据权限配置列表
    */
    private List<DataPrivilegeDto> findAllDataPrivilegeDto(){
        List<DataPrivilegeDto> dataPrivilegeDtoList=null;
        //先从redis缓存取
        if(this.redisService != null) {
            Object obj = this.redisService.get("dataPrivilegeDtoList");
            if(obj != null) {
                dataPrivilegeDtoList = (List)obj;
            }
        }
        //从数据库取
        if(dataPrivilegeDtoList!=null){
            String resourceList="";
            List<DataPrivilege> dataPrivilegeList=selectList(null);
            for(int i=0;i<dataPrivilegeList.size();i++){
                DataPrivilegeDto dataPrivilegeDto=new DataPrivilegeDto();
                dataPrivilegeDto.setDataType(dataPrivilegeList.get(i).getDataType());
                dataPrivilegeDto.setPrivilegeSql(dataPrivilegeList.get(i).getPrivilegeSql());
                //resourceList
                resourceList=dataPrivilegeDtlService.findDataPrivilegeDtlResource(dataPrivilegeList.get(i).getId());
                dataPrivilegeDto.setResourceList(resourceList);

                dataPrivilegeDtoList.add(dataPrivilegeDto);
            }
            //存入redis
            if(this.redisService != null) {
                this.redisService.set("dataPrivilegeDtoList", dataPrivilegeDtoList, redis_key_exp);
            }
        }
        return dataPrivilegeDtoList;
    }

    /*
    * 单个数据权限配置SQL拼接
    */
    public String handlerTablePrivilegeDtl(Long privilegeId, String resourceUrl, Long userId, String orgSql, String addSql) {
        List<DataPrivilegeDtlDto> dataPrivilegeDtlDtoList = this.dataPrivilegeDtlService.findDataPrivilegeDtlDto(privilegeId, resourceUrl);
        if(dataPrivilegeDtlDtoList != null && dataPrivilegeDtlDtoList.size() != 0) {
            Iterator dataPrivilegeDtlDtoIterator = dataPrivilegeDtlDtoList.iterator();
            while(dataPrivilegeDtlDtoIterator.hasNext()) {
                DataPrivilegeDtlDto dataPrivilegeDtlDto = (DataPrivilegeDtlDto)dataPrivilegeDtlDtoIterator.next();
                String tableName = dataPrivilegeDtlDto.getTableName();
                String columnName = dataPrivilegeDtlDto.getColumnName();
                if(orgSql.toLowerCase().contains(tableName.toLowerCase())) {
                    addSql = SqlUtils.matcherPrivilegeSql(addSql, userId);
                    orgSql = SqlUtils.handlerSql(orgSql, addSql, tableName, columnName);
                }
            }
            return orgSql;
        } else {
            return orgSql;
        }
    }

    /*
    * 数据权限配置SQL拼接
    */
    public String handlerTablePrivilege(String orgSql) {
        String resourceUrl = ThreadLocals.getResourceUrl();
        Long userId = ThreadLocals.getCurrentUser().getId();
        List<DataPrivilegeDto> dataPrivilegeDtoList = this.findAllDataPrivilegeDto();
        if(dataPrivilegeDtoList != null && dataPrivilegeDtoList.size() != 0) {
            Iterator dataPrivilegeDtoIterator = dataPrivilegeDtoList.iterator();
            while(dataPrivilegeDtoIterator.hasNext()) {
                DataPrivilegeDto dataPrivilegeDto = (DataPrivilegeDto)dataPrivilegeDtoIterator.next();
                String resourceList = dataPrivilegeDto.getResourceList();
                if(resourceList != null && resourceList.contains(resourceUrl)) {
                    String newAddSql = dataPrivilegeDto.getPrivilegeSql().toLowerCase();
                    orgSql = this.handlerTablePrivilegeDtl(dataPrivilegeDto.getId(), resourceUrl, userId, orgSql, newAddSql);
                }
            }
            return orgSql;
        } else {
            return orgSql;
        }
    }
}
